<template>
  <div :class="{'discount-info-back': isHasBackground}" class="discount-info">
    <Title :title="title" @click.native="getParams"/>
    <div class="discount-form">
      <el-form
        ref="discountForm"
        :model="discountForm"
        :rules="discountRules"
        label-position="left"
        class="edit-discount el-form-box-left"
        label-width="90px">
        <el-form-item v-if="!isCreate" label="成本确认" label-width="130px" prop="costConfirm" style="margin-bottom:8px;">
          <el-switch :disabled="isDisabledWithoutMicro" v-model="discountForm.costConfirm" :active-value="1" :inactive-value="0" class="fb-switch "/>
        </el-form-item>
        <div class="discount-list">
          <div v-for="(item,index) in discountForm.costList" :key="index" class="discount-item">
            <!-- 选择成本 -->
            <div v-if="isTalent(item)" class="discount-item-name text">{{ item.costName }}</div>
            <div v-else class="discount-item-name">
              <selectWithoutHttp
                v-model="item.costObj"
                :list-data="costListOptions.items"
                :item-max-width="240"
                placeholder="选择成本"
                key-name="costId"
                placement="right"
                show-tool-tip="summary"
                label-name="costName"
                value-type="object"
                filterable
                @changeInfo="channelChange(item, $event)"
              />
            </div>
            <!-- 输入金额 -->
            <div class="discount-item-input">
              <el-input
                v-if="Number(item.costType) === 3"
                v-model="item.price"
                :disabled="isDisabledWithoutMicro"
                name="costChannel"
                placeholder="请输入金额"
                class="width120"
                type="number"
                maxlength="9"
                size="small"
                oninput="if(value>999999999.00)value=999999999"
                @change="changeMaintenaceFee(item)">
                <template slot="append">
                  <el-tooltip v-if="item.taxPrice" :content="`含税:${item.taxPrice}`">
                    <div class="append-input">含税:{{ item.taxPrice || '' }}</div>
                  </el-tooltip>
                  <div v-else class="append-input">含税:{{ item.taxPrice || '' }}</div>
                </template>
              </el-input>
              <el-input
                v-else
                v-model="item.price"
                :disabled="isDisabledWithoutMicro || !!(discountForm.isAutoTalent && isTalent(item))"
                name="costChannel"
                placeholder="请输入金额"
                type="number"
                maxlength="9"
                size="small"
                oninput="if(value>999999999)value=999999999">
                <div v-if="isTalent(item) && talentOptions" slot="suffix" style="height:100%;">
                  <el-tooltip placement="top" effect="dark">
                    <div slot="content" style="max-width: 300px;">
                      <div style="margin-bottom:5px;">供应商：{{ talentOptions.channelName || '--' }}</div>
                      <div v-if="talentOptions.ruleName" style="margin-bottom:5px;">{{ talentOptions.ruleName || '' }}</div>
                      <div style="margin-bottom:5px;">公式：{{ talentOptions.formula || '--' }}</div>
                      <div>条件：{{ talentOptions.condition || '--' }}</div>
                    </div>
                    <div style="display:flex;align-items:center;height:100%;z-index:2;cursor:pointer;">
                      <img :src="fxIcon" style="width:16px;height:16px;" alt="">
                    </div>
                  </el-tooltip>
                </div>
              </el-input>
            </div>
            <!-- 选择供应商 -->
            <div class="discount-item-select">
              <el-input
                v-if="Number(item.costType) === 1"
                v-model.trim="item.miniTeskId"
                :disabled="isDisabledMicro"
                name="miniTeskId"
                class="width144"
                placeholder="请填写平台ID"
                type="text"
                size="small" >
                <template slot="prepend"><span style="color:#999;">ID</span> </template>
              </el-input>
              <selectWithoutHttp
                v-else
                :disabled="isDisabledWithoutMicro || !!(discountForm.isAutoTalent && isTalent(item))"
                v-model="item.channelId"
                :list-data="channelList"
                :item-max-width="180"
                show-tool-tip="value"
                placeholder="选择供应商"
                key-name="id"
                filterable
                label-name="supplier"
              />
            </div>
            <div v-if="isTalent(item)" class="switch-talent-mode">
              <el-switch v-model="discountForm.isAutoTalent" :active-value="1" :inactive-value="0" class="fb-switch"/>
              <div class="text">{{ discountForm.isAutoTalent?'自动':'手动' }}</div>
              <el-tooltip placement="top" effect="dark">
                <div slot="content" style="max-width: 200px;">自动生成成本：订单保存后才会根据最新订单数据更新达人成本</div>
                <tipIcon is-diy class="el-icon-warning-outline"/>
              </el-tooltip>
            </div>
            <div v-if="index > 0" class="delete-btn" @click="deleteCost(index)">
              <img :src="delIcon" alt="del">
            </div>
            <div v-if="index === (discountForm.costList.length - 1)" class="add-btn" @click="addCost()">
              <img :src="plusIcon" alt="del">
            </div>
          </div>
        </div>
      </el-form>
    </div>
  </div>
</template>
<script>
import { getClientName } from '@/api/select';
import { getSuppliers } from '@/api/mengli';
import Title from '@/components/Title';
import { costList } from '@/api/config';
import ElMessage from '@/utils/message';
import selectWithoutHttp from '@/components/Common/selectWithoutHttp';
import delIcon from '@/assets/del-icon.png';
import plusIcon from '@/assets/orderlist/plus.png';
import fxIcon from '@/assets/fx.png';

export default {
  name: 'DiscountInfo',
  components: { Title, selectWithoutHttp },
  props: {
    isDisabledWithoutMicro: {
      type: Boolean,
      default: false
    },
    isDisabledMicro: {
      type: Boolean,
      default: false
    },
    isCreate: {
      type: Boolean,
      default: false
    },
    talentOptions: {
      type: Object,
      default: () => {
        return null;
      }
    },
    isHasBackground: {
      type: Boolean,
      default: true
    },
    batchRemoteRequest: {
      type: String,
      default: 'remoteRequestDc'
    },
    isMakeUpOrder: { // 如果为真则是补差单不进行回填
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      delIcon,
      plusIcon,
      fxIcon,
      title: '成本信息',
      talentCostId: '',
      loadingSn: true,
      discountRules: {},
      discountForm: {
        isAutoTalent: 1,
        costConfirm: 1,
        costList: [
          { costName: '达人分成', costType: 2, costId: 2, price: '', channelId: '', category: 2 }
        ]
      },
      channelList: [],
      clientName: [],
      rebateCustomer: null,
      costListOptions: {
        items: []
      },
      isInsertState: false,
      isGetCostList: false
    };
  },
  watch: {
    'discountForm.starMapObj.starMapNum'(newV, oldV) {
      // console.log('返点', newV, oldV);
      if (!oldV && newV) {
        // 返点客户
        window.removeReadOnly();
        window.remoteRequest(`.${this.batchRemoteRequest}`, this.clientNameList);
      }
    }
  },
  mounted() {
    this.getChannel();
    this.getCostList();
    this.clientNameList(null, true);
  },
  methods: {
    // 编辑时注入数据
    insertDetail(item) {
      const itemClone = _.cloneDeep(item);
      const params = itemClone.costBreakdown;
      if (this.isMakeUpOrder) params.costList = [];
      params.costConfirm = params.costConfirm ? 1 : 0;
      if (params.costList) {
        params.costList.forEach(i => {
          if (i.costName === '达人分成' && !i.category) i.category = 2;
          // 数据回填
          if (!i.costObj && i.costId && i.costName) {
            i.costObj = { costId: i.costId, costName: i.costName };
          }
        });
      }
      const talentObj = { costName: '达人分成', costType: 2, price: '', channelId: '', category: 2 };
      if (!params.costList || params.costList.length === 0) {
        params.costList = [talentObj];
      } else if (params.costList[0].category !== 2) {
        // 把达人分成移到第一位
        let talentCost;
        params.costList = params.costList.filter(i => {
          if (i.category === 2) talentCost = i;
          return i.category !== 2;
        });
        if (talentCost) params.costList.unshift(talentCost);
      }
      // 如果返回的数据一条达人成本都没有，则在头部增加一条
      const hasTalent = params.costList.some(i => i.category === 2);
      if (!hasTalent) params.costList.unshift(talentObj);
      this.discountForm = params;
      if (this.isGetCostList) {
        this.freshCostData();
      }
      this.isInsertState = true;
    },
    /**
     * 请求数据
     */
    getCostList() {
      costList({ page: 1, perPage: 100, notShowNoAuthTip: !this.isGetCostList }).then(res => {
        if (res.data && res.data.items) {
          res.data.items = res.data.items.filter(i => {
            if (i.category === 2) this.talentCostId = i.costId; // 保存达人分成的id
            return i.category !== 2; // 剔除达人分成
          });
        }
        this.costListOptions = res.data;
        if (this.isInsertState) {
          this.freshCostData();
        }
        this.isGetCostList = true;
      }).catch(() => {
      });
    },
    freshCostData() {
      // 刷新discountForm里面的costList数据，因为有可能成本项已被更改
      if (this.discountForm.costList) {
        const newCostList = this.costListOptions.items;
        this.discountForm.costList.forEach(i => {
          for (let j = 0; j < newCostList.length; j++) {
            if (newCostList[j].costId === i.costId) {
              i.costName = newCostList[j].costName;
              i.costType = newCostList[j].costType;
              i.costObj = { costId: i.costId, costName: i.costName };
              break;
            }
          }
        });
      }
    },
    // 获取供应商的列表
    getChannel() {
      getSuppliers(1, 1000).then(res => {
        this.channelList = res.data.items;
      }, result => {
        // this.$message.error(result.message);
      });
    },
    clientNameList(query = null, notShowNoAuthTip = false) {
      getClientName(query, 1, notShowNoAuthTip).then(res => {
        this.clientName = res.data;
      }, result => {
        // this.$message.error(result.message);
      });
    },
    /**
     * 工具方法
     */
    addCost() {
      const obj = { costId: '', costName: '', costType: '', price: '', channelId: '' };
      this.discountForm.costList.push(obj);
    },
    deleteCost(index) {
      this.discountForm.costList.splice(index, 1);
    },
    isTalent(item) {
      return item.category === 2;
    },
    // 计算
    changeMaintenaceFee(item) {
      if (item.price || item.price === '0') {
        const rate = this.getTaxRate(item.costId, item.taxRate) || 0;
        const fee = Number(item.price) * rate;
        this.$set(item, 'taxPrice', fee.toFixed(2));
      } else {
        this.$set(item, 'taxPrice', '');
      }
    },
    getTaxRate(costId, itemTaxRate) {
      const costListArr = this.costListOptions.items || [];
      if (costListArr.length) {
        const item = costListArr.find(i => i.costId === costId);
        return item ? item.taxRate : itemTaxRate;
      }
      return itemTaxRate;
    },
    // 渠道商改变
    channelChange(item, costObj) {
      Object.assign(item, costObj);
      this.channelList[0].disabled = true;
    },
    // 提供给父组件来验证完整性
    validateForm(validate = true, index = 0) {
      return new Promise((resolve, reject) => {
        if (validate) {
          this.$refs.discountForm.validate(valid => {
            if (valid) {
              resolve(valid);
            } else {
              reject(index);
            }
          });
        } else {
          resolve(true);
        }
      });
    },
    validateEmpty(params) {
      let isRepeatChannel = false;
      let hasPriceEmpty = '';
      let hasMiniTeskIdEmpty = '';
      if (params.costList && params.costList.length > 0) {
        // 判空逻辑
        params.costList.forEach(i => {
          // 如果达人分成为手动则需要判断价格是否填写
          const talentPrice = i.category === 2 && !params.isAutoTalent && !i.price && i.price !== 0;
          const otherPrice = i.category !== 2 && !i.price && i.price !== 0;

          if (Number(i.costType) !== 1 && (talentPrice || otherPrice) && hasPriceEmpty === '') {
            hasPriceEmpty = i.costName;
          }
          if (Number(i.costType) === 1 && hasMiniTeskIdEmpty === '' && !i.miniTeskId && i.miniTeskId !== 0) {
            // 平台ID类型时需要判断平台ID必填
            hasMiniTeskIdEmpty = i.costName;
          }
        });
        // 判断是否有成本完全一样
        for (let i = 0; i < params.costList.length; i++) {
          for (let j = i + 1; j < params.costList.length; j++) {
            const isNotId = Number(params.costList[i].costType) !== 1; // 类型
            // costType 1: 平台ID  2: 供应商  3: 供应商+含税
            const isSameCostId = params.costList[i].costId === params.costList[j].costId; // 成本id是否相同
            const isSameChannelId = params.costList[i].channelId === params.costList[j].channelId; // 渠道商是否相同
            const isSameId = params.costList[i].miniTeskId === params.costList[j].miniTeskId; // ID是否相同
            if (isNotId && isSameCostId && isSameChannelId) {
              isRepeatChannel = `所选择的${params.costList[i].costName}有重复供应商`;
              break;
            }
            // 当成本类型为平台ID时，判断ID是否相同
            if (!isNotId && isSameCostId && isSameId) {
              isRepeatChannel = `所选择的${params.costList[i].costName}有重复ID`;
              break;
            }
          }
        }
      }
      if (isRepeatChannel) {
        ElMessage.error(isRepeatChannel);
        return false;
      }
      if (hasPriceEmpty !== '') {
        ElMessage.error(`请填写${hasPriceEmpty}的价格`);
        return false;
      }
      if (hasMiniTeskIdEmpty !== '') {
        ElMessage.error(`请填写${hasMiniTeskIdEmpty}的平台ID`);
        return false;
      }
      return true;
    },
    // 提供给父组件来获取参数
    getParams() {
      const params = _.cloneDeep(this.discountForm);
      // 判断是否存在成本与供应商都一样的两项，如果有则不符合
      if (params.costList && params.costList.length > 0) {
        params.costList = params.costList.filter(i => !!i.costName);
        // 判空逻辑
        params.costList.forEach(i => {
          // 达人分成逻辑
          if (i.category === 2) {
            i.costId = this.talentCostId || i.costId;// 刷新达人分成ID
          }
          if (i.price) i.price = Number(i.price);
          if (!i.id) i.id = 0;
          delete i.costObj;
        });
      }
      return params;
    },
    // 处理价格单位, type: 1 元转成分   type: 2 分转成元
    formatPrice(params, type = 1) {
      const costWord = [
        'costChannel', 'talentDividends',
        'maintenanceFeePaid', 'maintenanceFee', 'rebatePaid', 'rebate',
        'starMapNum', 'fansTop', 'douNum', 'miniTeskCost'
      ];
      for (const i in params) {
        if (costWord.includes(i) && params[i]) {
          if (type === 1) {
            params[i] = (params[i] * 100).toFixed(0);
          } else {
            params[i] = params[i] / 100;
          }
        }
        if (typeof params[i] === 'object') {
          for (const j in params[i]) {
            if (costWord.includes(j) && params[i][j]) {
              if (type === 1) {
                params[i][j] = (params[i][j] * 100).toFixed(0);
              } else {
                params[i][j] = params[i][j] / 100;
              }
            }
          }
        }
      }
      return params;
    }
  }
};
</script>
<style lang="scss" scoped>
.discount-info-back {
   width:100%;
    background:rgba(255,255,255,1);
    box-shadow:2px 4px 13px 0px rgba(221,225,234,1);
    border-radius:12px;
    margin-top: 12px;
    padding: 24px;
}
.discount-info {
  .edit-discount {
    margin-top: 32px;
    // display: flex;
    flex-wrap: wrap;
    & ::v-deep {
    .el-form-item {
        .el-textarea__inner {
          height: 64px !important;
        }
        .el-form-item__label {
          width: 80px !important;
          line-height: 1.1 !important;
          display: flex;
          align-items: center;
          height: 32px;
          padding-left: 0;
        }
      }
    }
  }
  .mr108 {
    margin-right: 108px;
  }
}

.discount-list {
  .discount-item {
    position: relative;
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    .discount-item-name {
      color: #666;
      font-size: 14px;
      width: 120px;
      flex-shrink: 0;
      margin-right: 10px;
      // &.text {
      //   display: flex;
      //   align-items: center;
      //   border: 1px solid rgb(220, 223, 230);
      //   border-radius: 4px;
      //   height: 30px;
      //   padding: 0 15px;
      //   font-size: 13px;
      //   cursor: not-allowed;
      //   background-color: #F5F7FA;
      //   border-color: #E4E7ED;
      //   color: #C0C4CC;
      // }
      &::v-deep {
        .el-select {
          width: 120px;
          .el-input__inner {
          padding-left: 8px;
            width: 120px;
          }
        }
      }
    }
    .discount-item-input {
      width: 240px;
      margin-right: 15px;
    }
    .discount-item-select {
      position: relative;
      display: flex;
      align-items: center;
      &::v-deep {
        .el-input__inner {
          width: 200px;
        }
      }
    }
    &::v-deep {
      .el-input-group__prepend {
        width: 57px;
      }
      .el-input-group__append {
        padding: 0 10px;
        .append-input {
          width: 100px !important;
          color: #999;
          text-overflow: ellipsis;
          overflow: hidden;
        }
      }
    }
  }
}
.switch-talent-mode {
  // position: absolute;
  // right: -110px;
  // top: 5px;
  margin-left: 10px;
  display: flex;
  align-items: center;
  .text {
    margin-left: 5px;
    font-size: 13px;
    color: #999;
  }
  .el-icon-warning-outline {
    color: #999;
    font-size: 13px;
    margin-left: 10px;
    cursor: pointer;
  }
}
.add-btn {
  width: 32px;
  height: 32px;
  background: #EFF3FB;
  border-radius: 4px;
  color: #406EFF;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-left: 10px;
  cursor: pointer;
  img  {
    width: 16px;
  }
}
.delete-btn {
  width: 32px;
  height: 32px;
  margin-left: 10px;
  cursor: pointer;
  img {
    width: 100%;
  }
}
.width144 {
  &::v-deep {
    .el-input__inner {
      width: 144px !important;
    }
  }
}
.width120{
  &::v-deep {
    .el-input__inner {
      width: 120px !important;
    }
  }
}

</style>
